package com.hqj.demo;

import javax.swing.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 登录操作类
 */
public class Login {

    User loginUser = null;
    Map<String,User> map = null;
    List<Questions> list = null;
    Properties pro = null;
    private static File f1 = new File("D:\\Workspaces\\Idea\\Java202006\\java基础的综合练习\\dirs");
    private static File f2 = new File(f1,"user.txt");
    private static File f3 = new File(f1,"questions.txt");
    private static File f4 = new File(f1,"score.properties");
    static{
        FileUtil.createDir(f1);
        FileUtil.createFile(f2);
        FileUtil.createFile(f3);
        FileUtil.createFile(f4);
    }

    public Login(){
        map = (Map<String, User>) FileUtil.objectInput(f2);
        if(map==null){
            map = new HashMap<>();
            map.put("t01",new Teacher("t01","测试老师01","tea","男","123",10));
        }
        list = (List<Questions>) FileUtil.objectInput(f3);
        if(list==null){
            list = new ArrayList<>();
        }
        pro = FileUtil.proLoad(f4);
        if(pro==null){
            pro = new Properties();
        }

    }

    public void main(){
        System.out.println("1-注册，2-学生登录，3-老师登录，0-退出程序");
    }

    public void register(){
        System.out.println("--------------进入到注册页面-------------");
        String loginName = inputDig("请输入登录名:");
        //通过对map key值判断是否包含
        if(map.containsKey(loginName)) {
            JOptionPane.showMessageDialog(null,"注册失败!("+loginName+")该登录名已经存在");
            return;//结束程序
        }
        String userName = inputDig("请输入用户名:");
        String password = inputDig("请输入密码:");
        String pwd = inputDig("请输入确认密码:");
        if(!password.equals(pwd)){
            JOptionPane.showMessageDialog(null,"注册失败!两次密码输入不一致");
            return;//结束程序
        }
        String sex = inputDig("请输入性别(1:男，2：女):");

        User u = new Student(loginName,userName,"stu",sex,password,0);
        map.put(u.getLoginName(),u);
        //把对象通过对象流写入到文件
        FileUtil.objectOutput(f2,map);
        JOptionPane.showMessageDialog(null,"注册成功!");

        System.out.println("--------------注册完成-------------");
    }

    public void login(){
        String loginName = inputDig("请输入登录名:");
        String password = inputDig("请输入密码:");
        if(!map.containsKey(loginName)){
            JOptionPane.showMessageDialog(null,"登录名错误，登录失败!");
            return;
        }
        //利用登录名获取出用户信息
        User u = map.get(loginName);
        if(!password.equals(u.getPassword())){
            JOptionPane.showMessageDialog(null,"密码错误，登录失败!");
            return;
        }

        JOptionPane.showMessageDialog(null,"登录名成功!");
        //把登录成功的用户信息存放到全局变量
        this.loginUser = u;
        while(true) {
            this.index();
        }
    }

    public void index(){

        if("stu".equals(this.loginUser.getType())){
            System.out.println("学生登录成功首页(菜单1-显示用户信息，2-修改用户密码，3-去测试，4-查看成绩，0-退出系统)");
        }else{
            System.out.println("老师登录成功首页(菜单1-显示用户信息，2-修改用户密码，3-出题，4-查看题目及选项，0-退出系统)");
        }
        Scanner scan = new Scanner(System.in);
        try {
            int a = scan.nextInt();
            if(a>=0&&a<=4){
                switch (a){
                    case 0:
                        System.exit(0);
                        return;
                    case 1:
                        showMsg();
                        break;
                    case 2:
                        updatePwd();
                        break;
                    case 3:
                        if("stu".equals(this.loginUser.getType())) test();
                        else title();
                        break;
                    case 4:
                        if("stu".equals(this.loginUser.getType())) lookScore();
                        else lookTitle();
                        break;
                }
            }else{
                System.out.println("输入内容不规范");
            }

        }catch (Exception e){
            System.out.println("输入内容格式不正确,错误信息内容:"+e.getMessage());
        }

    }

    public void showMsg(){
        System.out.println("-------------显示个人信息---------------");
        System.out.println(this.loginUser);
    }

    public void updatePwd(){
        System.out.println("---------------修改密码---------------------");
        String oldPwd = inputDig("请输入旧密码:");
        if(!oldPwd.equals(this.loginUser.getPassword())){
            JOptionPane.showMessageDialog(null,"旧密码输入错误，修改失败!");
            return;
        }
        String newPwd = inputDig("请输入新密码:");
        String pwd = inputDig("请输入确认密码:");
        if(!newPwd.equals(pwd)){
            JOptionPane.showMessageDialog(null,"两次密码输入不一致，修改失败!");
            return;
        }

        this.loginUser.setPassword(newPwd);
        map.put(this.loginUser.getLoginName(),this.loginUser);

        //重新覆盖user.txt
        FileUtil.objectOutput(f2,map);
        JOptionPane.showMessageDialog(null,"密码修改成功!");
        System.out.println("---------------密码修改完成---------------------");

    }

    public void test(){
        int score = 0;
        Scanner scan = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        Set<Integer> ins = new HashSet<>();
        Random r = new Random();
        for(int i=0;i<(list.size()<10?list.size():10);) {
            int index = r.nextInt(this.list.size()) + 0;//1
            int size = ins.size();
            ins.add(index);//1
            if(ins.size()==size){//表示下标值出现了重复
                continue;
            }
            i++;
        }
        int i = 1;
        for(Integer index:ins){
            Questions q = list.get(index);
            System.out.print("第"+(i++)+"题:");
            q.showTitle();

            System.out.print("请输入你的选择(字母不区分大小写):");
            String answer = scan.next();
            boolean b = q.isRight(answer);
            System.out.println("回答"+(b?"正确得分:"+q.getScore():"错误得分:0"));
            score += b?q.getScore():0;
        }

        if(this.loginUser instanceof Student){
            Student student = (Student)loginUser;
            student.setScore(score);
            map.put(student.getLoginName(),student);
            FileUtil.objectOutput(f2,map);
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        pro.setProperty(this.loginUser.getLoginName(),sdf.format(new Date())+"做题得分:"+score);
        FileUtil.proStore(f4,pro);
        System.out.println("完成测试，最后得分:"+score);
    }

    public void lookScore(){
        String score = pro.getProperty(this.loginUser.getLoginName());
        System.out.println(this.loginUser.getUserName()+"在"+score);
    }

    public void title(){

        System.out.println("------------进入出题界面-----------");

        String type = inputDig("请输入题型1：单选，其他多选").equals("1") ? "单选" : "多选";
        String text = inputDig("请输入" + type + "题的题目:");
        String options[] = createOptions();
        String answer = inputDig("请输入" + type + "题的正确答案:");
        int score = 0;
        try {
            score = Integer.parseInt(inputDig("请输入分数:"));
        }catch (Exception e){
            System.out.println("分数输入错误，必须为数字，默认为5分");
            score = 5;
        }

        Questions q = null;
        if("单选".equals(type)){
            q = new SingleCheck(text,options,type,answer,score);
        }else{
            q = new MutilCheck(text,options,type,answer,score);
        }

        this.list.add(q);
        //写入到questions.txt
        FileUtil.objectOutput(f3,list);
        JOptionPane.showMessageDialog(null,type+"题,出题完成！");
    }

    public String[] createOptions(){
        String options[] = new String[0];
        char c = 'A';
        while(true){
            String option = c+":"+inputDig("请输入选择"+c+"的内容:");
            //数组的长度自动增长
            options = Arrays.copyOf(options,options.length+1);
            //赋值到增长的位置
            options[options.length-1] = option;
            String msg = inputDig("是否继续添加1：继续，其他退出");
            if(!"1".equals(msg)){
                break;
            }
            c++;//字符字母的ASCII码值的递增 A->B->C
        }

        return options;
    }

    public void lookTitle(){
        for(Questions q:this.list){
            q.showTitle();
            System.out.println("正确答案:"+q.getAnswer());
        }
    }



    public String inputDig(String msg){
        return JOptionPane.showInputDialog(msg);
    }

}
